//
//  YDHomeAdvertisementView.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/29.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDHomeAdvertisementView.h"
#import "YDHomeAdvertisementCell.h"
#import "YDHomeRotationModel.h"


@interface YDHomeAdvertisementView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    NSTimer *timer;
}
@property (nonatomic , weak) UIView *redLine;
@property (nonatomic , weak) UIImageView *hornImage;
@property (nonatomic , strong) NSMutableArray *cellWidthsArray;
@property (nonatomic , assign) CGFloat cellAllWidth;
@property (nonatomic,weak) UICollectionView *collectionView;


@end

@implementation YDHomeAdvertisementView

-(NSMutableArray *)cellWidthsArray
{
    if (_cellWidthsArray == nil) {
        _cellWidthsArray = [NSMutableArray array];
    }
    return _cellWidthsArray;
}

-(void)setModelArray:(NSMutableArray *)modelArray
{
    _modelArray = modelArray;
    if (!modelArray.count) {
        if (_collectionView != nil) {
            [self.cellWidthsArray removeAllObjects];
            [self removeTimer];
            [self.collectionView reloadData];
        }
        return;
    }
//    if (!modelArray.count)return;
    [self.cellWidthsArray removeAllObjects];
    [self removeTimer];
    
    [self collectionView];
    __block CGFloat cellAllWidth = 0.0;
    [modelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        YDHomeRotationModel *model = (YDHomeRotationModel *)obj;
        CGFloat stringWidth = [model.content boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:font12ScreenWRate * LKScreenW]} context:nil].size.width;
        [self.cellWidthsArray addObject:[NSNumber numberWithFloat:stringWidth]];
        cellAllWidth += stringWidth;
    }];
    self.cellAllWidth = cellAllWidth;
    [self.collectionView reloadData];
    [self addTimer];

}
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        [self redLine];
        [self hornImage];
        
    }
    return self;
}
+(instancetype)homeAdvertisementViewWithFrame:(CGRect)frame ModelArray:(NSArray *)modelArray
{
    YDHomeAdvertisementView *view = [[self alloc] initWithFrame:frame];
    view.modelArray = [modelArray mutableCopy];
    return view;
}

-(UIView *)redLine
{
    if (_redLine == nil) {
        UIView *redLine = [[UIView alloc] init];
        [self addSubview:redLine];
        redLine.backgroundColor = NumberColor(226, 96, 66);
        redLine.backgroundColor = [UIColor clearColor];
        [redLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(self);
            make.width.equalTo(@2);
        }];
        _redLine = redLine;
    }
    return _redLine;
}
-(UIImageView *)hornImage
{
    if (_hornImage == nil) {
        UIImageView *hornImage = [[UIImageView alloc] init];
        [self addSubview:hornImage];
        hornImage.backgroundColor = [UIColor clearColor];
        hornImage.contentMode = UIViewContentModeScaleAspectFit;
        hornImage.image = [UIImage imageNamed:@"h-sy-gonggao"];
        [hornImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self);
            make.left.equalTo(self).offset(10);
            make.width.height.equalTo(@(rate375(16)));
        }];
        _hornImage = hornImage;
    }
    return _hornImage;
}
/**
 懒加载
 */
-(UICollectionView *)collectionView
{
    if (_collectionView == nil)
    {
        
        CGFloat viewX = rate375(38);
        CGFloat viewY = 0;
        CGFloat viewW = rate375(325);
        CGFloat viewH = self.height;
        CGRect viewFrame = CGRectMake(viewX, viewY, viewW, viewH);
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:viewFrame collectionViewLayout:flowLayout];
        [self addSubview:collectionView];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.scrollEnabled = NO;
        [collectionView registerClass:[YDHomeAdvertisementCell class] forCellWithReuseIdentifier:@"YDHomeAdvertisementCell"];
        _collectionView = collectionView;
    }
    return _collectionView;
}

#pragma mark - NSTimer
/**
 * 添加定时器
 */
- (void)addTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(scrollCollectionView) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:5]];
}

/**
 * 移除定时器
 */
- (void)removeTimer
{
    if (timer.isValid)
    {
        [timer invalidate];
        timer = nil;
    }
}

- (void)scrollCollectionView
{
    CGFloat x= self.collectionView.contentOffset.x;
//    CGFloat lastWidth = [self.cellWidthsArray.lastObject floatValue];
    if (x < self.cellAllWidth - 150)
    {
        self.collectionView.contentOffset = CGPointMake(x+1, 0);
    }
    else
    {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        CGFloat socroll_x = 0;
        self.collectionView.contentOffset = CGPointMake(socroll_x , 0);
        
        [self removeTimer];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self addTimer];
        });
        
        
        
    }
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.cellWidthsArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YDHomeAdvertisementCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YDHomeAdvertisementCell" forIndexPath:indexPath];
    YDHomeRotationModel *model = self.modelArray[indexPath.item];
    cell.noticeLabel.text = model.content;
    NSNumber *floatNumber = self.cellWidthsArray[indexPath.item];
    cell.noticeLabel.frame = CGRectMake(0, 0, [floatNumber floatValue], self.height);
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *floatNumber = self.cellWidthsArray[indexPath.item];
    return CGSizeMake([floatNumber floatValue], self.height);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    DDLog(@"++++%zd",indexPath.row)
    if ([self.delegate respondsToSelector:@selector(homeAdvertisementView:didClickCellIndex:)]) {
        [self.delegate homeAdvertisementView:self didClickCellIndex:indexPath.item];
    }
}

-(void)dealloc
{
    [self removeTimer];
}

@end
